package cn.wsalix.shop.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.anlaser.service.impl.SimpleServiceImpl;
import cn.wsalix.shop.entity.Product;
import cn.wsalix.shop.entity.Price;
import cn.wsalix.shop.form.PriceForm;
import cn.wsalix.shop.repository.PriceRepository;
import cn.wsalix.shop.service.PriceService;
import cn.wsalix.status.PriceEnum;
import cn.anlaser.utils.SearchFilter;
import cn.anlaser.utils.SearchFilter.Operator;

@Service("priceService")
public class PriceServiceImpl
		extends
		SimpleServiceImpl<PriceForm, PriceRepository, Price>
		implements PriceService {
	@Autowired
	private PriceRepository productPriceRepository;

	@Override
	public String module() {
		return "/admin/price";
	}

	@Override
	public PriceRepository getRepository() {
		return productPriceRepository;
	}

	@Transactional
	@Override
	public Price add(PriceForm form) {
		Product product = form.getProduct();
		/*if (product == null) {
			if (form.getProductId() != null && form.getProductId() != 0) {
				product = productService.findById(form.getProductId());
				form.setProduct(product);
			}
			// TODO 无产品信息，抛出异常
		}*/
		switch (form.getType()) {
		case showing:
			product.setPriceSrc(form.getPrice());
			if (product.getPrice() == null || product.getPrice() == 0) {
				product.setPrice(form.getPrice());
			}
			break;
		case discount:
			/*
			 * if (entity.getPrice() < product.getPrice()) {
			 * product.setPrice(entity.getPrice()); }
			 */
			break;
		case original:
			product.setPrice(form.getPrice());
			break;
		case tuan:
			product.setTuan(true);
			product.setTuanNum(form.getTuanNum());
			product.setPriceTuan(form.getPrice());
			break;
		default:
			break;
		}
		//productService.edit(product);

		return super.add(form);
	}

	@Transactional
	@Override
	public Price edit(PriceForm entity) {		
		return super.edit(entity);
	}

	@Override
	public Class<Price> getEntityClazz() {
		return Price.class;
	}

	@Override
	public Map<String, SearchFilter> buildByForm(PriceForm form) {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		if (form.getProductId() != null && form.getProductId() != 0) {
			filters.put("product.id", new SearchFilter("product.id",
					Operator.EQ, form.getProductId()));
		}
		return filters;
	}

	@Transactional
	@Override
	public void addByProduct(Product entity) {
		PriceForm form = new PriceForm();
		form.setType(PriceEnum.original);
		form.setProduct(entity);
		form.setPrice(entity.getPrice());
		add(form);
	}

	/*
	 * @Override public void update(Observable o, Object arg) { if (o instanceof
	 * ProductChangeService) { ProductForm form = (ProductForm) arg; edit(form);
	 * } }
	 */
}
